<template>
  <div class="user-profile">
    <h1>用户主页</h1>

    <el-form :model="userForm"
             style="width: 450px" label-width="120px"
             class="user-form"
             :rules="rules"
             ref="userFormRef">

      <el-form-item label="修改用户头像" prop="avatarUrl">
          <el-upload
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleChange"
            :limit="1">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <!-- 预览图 -->
          </el-upload>
      </el-form-item>
      <img :src="uploadedImagePreview || require('@/assets/images/default.png')" alt="预览图"
           style="max-width: 100%; max-height: 200px; display: block; margin: 0 auto;
            border-radius: 50%;
            margin-bottom:20px" />
      <el-form-item label="用户名">
        <el-input v-model="userForm.userName" disabled></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="userForm.nickName"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userForm.phone" ></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="userForm.sex" placeholder="请选择性别" style="width: 100%">
          <el-option label="男" value="0"></el-option>
          <el-option label="女" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="当前密码">
        <el-input v-model="userForm.currentPassword" type="password" show-password disabled></el-input>
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="userForm.newPassword" type="password" show-password></el-input>
      </el-form-item>

      <el-form-item label="确认新密码" prop="password">
        <el-input v-model="userForm.password" type="password" show-password></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存更改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { uploadPicture } from '@/api/upload'
import { update } from '@/api/user'

export default {
  name: 'SysUserInfo',
  computed: {
    ...mapGetters([
      'name',
      'avatar',
      'password',
      'nickName',
      'email',
      'phone',
      'sex'
    ])
  },
  created() {
    this.userForm.userName = this.name;
    this.userForm.avatarUrl = this.avatar;
    this.userForm.nickName = this.nickName;
    this.userForm.email = this.email;
    this.userForm.phone = this.phone;
    this.userForm.sex = this.sex==='0'?'男':'女';
    this.userForm.currentPassword = this.password;
    this.uploadedImagePreview = "https://jinghaiyang.oss-cn-beijing.aliyuncs.com/app/upload/"+this.userForm.avatarUrl;
  },
  data() {
    const validatePassword = (rules, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'));
      } else if (value !== this.userForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    return {
      rules: {
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式不正确', trigger: 'blur' }
        ]
      },
      userForm: {
        avatarUrl: '',
        username: this.name,
        currentPassword: '', // 这里通常不应该显示明文密码，仅作示例
        newPassword: '',
        nickName: '',
        password: '',
        userId:'',
        email: '',
        phone: '',
        sex: ''
      },
      uploadStatus: '',
      uploadedImageFile: null, // 存储原始文件对象
      uploadedImagePreview: null, // 存储本地预览地址
    };
  },
  methods: {
    handleChange(file) {
      const rawFile = file.raw;
      if (!rawFile) return;
      // 只允许一个文件
      this.uploadedImageFile = rawFile;
      // 创建本地预览地址
      const previewUrl = URL.createObjectURL(rawFile);
      this.uploadedImagePreview = previewUrl;
      console.log("uploadedImagePreview",this.uploadedImagePreview)
    },
    onSubmit() {
      this.$refs.userFormRef.validate(valid => {
        if (valid) {
          // 验证通过，继续提交逻辑
          if (this.uploadedImageFile) {
            const formData = new FormData();
            formData.append("file", this.uploadedImageFile);
            uploadPicture(formData).then(res => {
              if (res.code === 20000) {
                this.userForm.avatarUrl = res.data;
                this.submitOrderForm();
              } else {
                this.$message.error('图片上传失败');
              }
            }).catch(() => {
              this.$message.error('图片上传出错');
            });
          } else {
            this.submitOrderForm();
          }
        } else {
          this.$message.error('请检查表单内容');
          return false;
        }
      });
    },
    submitOrderForm(){
          const submitData = {
            avatar: this.userForm.avatarUrl,
            userName: this.userForm.userName,
            nickName: this.userForm.nickName,
            password: this.userForm.newPassword
          };
          update(submitData).then(res => {
            if (res.code === 20000) {
              this.$message({
                message: '修改成功!',
                type: 'success',
                duration: 1200
              });
              this.$router.push({ path: '/dashboard' });
              this.$store.state.user.avatar = this.userForm.avatarUrl;
              this.$store.state.user.nickName = this.userForm.nickName;
              this.$store.state.user.password = this.userForm.newPassword;
              this.$store.state.user.name = this.userForm.userName;
              this.$store.state.user.email = this.userForm.email;
              this.$store.state.user.phone = this.userForm.phone;
              this.$store.state.user.sex = this.userForm.sex;
            } else {
              this.$message.error('修改失败');
            }
          })
        }
      }
    }
</script>


<style scoped lang="scss">
.user-form{

}
</style>
